'use strict';

const path = require('path');
const nconf = require('nconf');

module.exports = app => {

    // Mock Data
    nconf.use('file', {
        file: path.join(app.config.baseDir, 'app/mock/db.json'),
    });

    class Model {
        constructor(ctx) {
            this.ctx = ctx;
        }

        async getClient(clientId, clientSecret) {
            console.log('getClient clientId:', clientId, 'clientSecret:', clientSecret);
            // const client = nconf.get('client');
            // if (clientId !== client.clientId || clientSecret !== client.clientSecret) {
            //     return;
            // }
            return {
                // "id": 1,
                clientId: 'my_app',
                // "clientSecret": "my_secret",
                // "redirectUris": [
                //     "http://implements.io"
                // ],
                // "refreshTokenLifetime": 0,
                // "accessTokenLifetime": 0,
                grants: [
                    'password'
                ]
            };
        }

        async getUser(username, password) {
            console.log('getUser username:', username, 'password:', password);
            // const user = nconf.get('user');
            // if (username !== user.username || password !== user.password) {
            //     return;
            // }
            return {
                username,
                password
            };
        }

        async getAccessToken(bearerToken) {
            console.log('getAccessToken');
            const token = nconf.get('token');
            token.accessTokenExpiresAt = new Date(token.accessTokenExpiresAt);
            token.refreshTokenExpiresAt = new Date(token.refreshTokenExpiresAt);
            const user = nconf.get('user');
            const client = nconf.get('client');
            token.user = user;
            token.client = client;
            return token;
        }

        async saveAuthorizationCode(token, client, user) {
            console.log('saveToken');
            const _token = Object.assign({}, token, { user }, { client });
            nconf.set('token', _token);
            nconf.save();
            return _token;
        }
    }

    return Model;
};
